﻿# region Using Directives

using System;
using System.ComponentModel;
using System.ComponentModel.Composition;
using System.IO;
using System.Linq;
using EnvDTE;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.TeamArchitect.PowerTools.Features;

#endregion

namespace FeatureBuilder.ContribLib.Commands
{
    [DisplayName("Open File")]
    [Description("Opens a File.")]
    [Category("IDE")]
    public class OpenFile : FeatureCommand
    {
        // Declared public properties will be exposed in the Command Bindings property
        public string ProjectName { get; set; }
        public string ItemName { get; set; }

        /// <summary>
        /// Gets the ServiceProvider that we will use to get a reference to DTE.
        /// </summary>
        [Import(typeof(SVsServiceProvider))]
        public IServiceProvider ServiceProvider { get; private set; }

        /// <summary>
        /// Gets the Feature Extension instance for this invocation
        /// of the Condition
        /// </summary>
        [Import(AllowDefault = true)]
        public IFeatureExtension Feature { get; private set; }

        # region Overrides

        /// <summary>
        /// Called when any launch point bound to a command binding which refers to this command
        /// is invoked
        /// </summary>
        public override void Execute()
        {
            var dte = ServiceProvider.GetService(typeof(DTE)) as EnvDTE.DTE;
            if (dte == null)
                return;

            foreach (var filePath in from Project p in dte.Solution.Projects
                                     where p.Name == ProjectName
                                     select Path.GetDirectoryName(p.FullName)
                                         into folderPath
                                         select Path.Combine(folderPath, ItemName))
            {
                dte.StatusBar.Text = "Opening file " + ItemName;
                dte.ItemOperations.OpenFile(filePath);
                dte.StatusBar.Text = "Ready";
            }
        }

        #endregion
    }
}